package utils;

import entity.CommonParam;
import entity.HttpResult;
import swings.panels.WorkPanel;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: runoob
 * @date:
 */
public class HttpsUtil {

    public static HttpResult doGet(String toURL, String data, ArrayList<CommonParam> headersList, WorkPanel workPanel) {
        URL url;
        BufferedReader send_in;
        StringBuilder stringBuilder = new StringBuilder();
        HttpResult result = new HttpResult();
        try {
            url = new URL(toURL + data);
            //打开和URL之间的连接
            URLConnection connection = url.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection)connection;
            //设置通用的请求属性
            httpUrlConnection.setRequestProperty("accept", "*/*");
            httpUrlConnection.setRequestProperty("connection", "Keep-Alive");
            httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//建立连接
            for (CommonParam param : headersList){
                httpUrlConnection.setRequestProperty(param.getKey(), param.getValue());
            }
            httpUrlConnection.setConnectTimeout(5000);
            httpUrlConnection.setReadTimeout(5000);
            long start = System.currentTimeMillis();
            httpUrlConnection.connect();
            long stop = System.currentTimeMillis();
            //定义BufferedReader输入流来读取URL的响应
            send_in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while((line = send_in.readLine()) != null){
                stringBuilder.append(line);
            }

            Map<String, List<String>> map = httpUrlConnection.getHeaderFields();
            Map<String, String> headerMap = new HashMap();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                headerMap.put(entry.getKey(), entry.getValue().get(0));
            }
            result.setData(stringBuilder.toString());
            result.setHeaderMap(headerMap);
            result.setStatus(httpUrlConnection.getResponseCode() + "");
            result.setTime((stop - start) + "ms");
        } catch (IOException e) {
//            setInfo(e, workPanel);
        }
        return result;
    }

    public static HttpResult doPost(String toURL, String data, ArrayList<CommonParam> headersList, WorkPanel workPanel) throws Exception {
        long start = System.currentTimeMillis();
        HttpResult result = new HttpResult();
        StringBuilder bs = new StringBuilder();
        try {
            URL sendUrl = new URL(toURL.trim());
            URLConnection connection = sendUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection)connection;
            httpUrlConnection.setConnectTimeout(30000);
            httpUrlConnection.setReadTimeout(30000);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setRequestProperty("accept", "*/*");
            httpUrlConnection.setRequestProperty("connection", "Keep-Alive");
            httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            for (CommonParam param : headersList){
                httpUrlConnection.setRequestProperty(param.getKey(), param.getValue());
            }
//        connection.setRequestProperty("Content-Type","application/json;chert=UTF-8");
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            out.write(data);
            out.flush();
            out.close();
            httpUrlConnection.connect();
            InputStream is = httpUrlConnection.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String l;
            while ((l = buffer.readLine()) != null) {
                bs.append(l);
            }
            Map<String, List<String>> map = httpUrlConnection.getHeaderFields();
            Map<String, String> headerMap = new HashMap();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                headerMap.put(entry.getKey(), entry.getValue().get(0));
            }
            long stop = System.currentTimeMillis();
            result.setData(bs.toString());
            result.setHeaderMap(headerMap);
            result.setStatus(httpUrlConnection.getResponseCode() + "");
            result.setTime((stop - start) + "ms");
        }catch (IOException e) {
//            setInfo(e, workPanel);
        }
        return result;
    }

//    private static void setInfo(IOException e, WorkPanel workPanel){
//        StringWriter sw = new StringWriter();
//        try(PrintWriter pw = new PrintWriter(sw)){
//            e.printStackTrace(pw);
//        }
//        String errorInfo = sw.toString();
//        workPanel.repInfoPanel.setData(errorInfo);
//        workPanel.repDataBtn.setRelease();
//        workPanel.repBodyBtn.setRelease();
//        workPanel.repHeadersBtn.setRelease();
//        workPanel.repInfoBtn.setHold();
//        workPanel.repDataPanel.setVisible(false);
//        workPanel.repBodyPanel.setVisible(false);
//        workPanel.repHeadersPanel.setVisible(false);
//        workPanel.repInfoPanel.setVisible(true);
//    }

}
